import React, { useMemo, useState } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Table,
  Space,
  Modal,
  Tag,
  DatePicker,
  InputNumber,
  message,
} from 'antd';
import {
  TeamOutlined,
  PlusOutlined,
  TagsOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@ant-design/icons';

const { Option } = Select;

export default function TempUserList() {
  const [form] = Form.useForm();
  const [data, setData] = useState(() => (
    Array.from({ length: 10 }).map((_, i) => ({
      id: i + 1,
      account: `temp_${i + 1}`,
      nickName: `临时用户${i + 1}`,
      tagName: i % 3 === 0 ? '活动A' : '活动B',
      remark: i % 2 === 0 ? '—' : '限时',
      expireTime: i % 3 === 0 ? '2023-12-31 23:59:59' : '2030-01-01 00:00:00',
      mobile: `1390000${String(200 + i)}`,
      email: `temp${i + 1}@example.com`,
      printPoints: Math.floor(Math.random() * 100),
      printNumLimit: Math.floor(Math.random() * 50),
      createBy: i % 2 === 0 ? 'admin' : 'operator',
      createTime: `2025-03-${(i % 28) + 1} 10:00:00`,
    }))
  ));
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const [newOpen, setNewOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [currentRow, setCurrentRow] = useState(null);
  const [tagOpen, setTagOpen] = useState(false);
  const [renewOpen, setRenewOpen] = useState(false);
  const [renewalType, setRenewalType] = useState(1);
  const [tags, setTags] = useState([
    { id: 1, name: '活动A' },
    { id: 2, name: '活动B' },
    { id: 3, name: '活动C' },
  ]);

  const columns = useMemo(() => ([
    { title: '昵称', dataIndex: 'nickName', width: 120 },
    { title: '账号', dataIndex: 'account', width: 140 },
    { title: '标签', dataIndex: 'tagName', width: 100, render: (name) => <Tag>{name}</Tag> },
    { title: '备注', dataIndex: 'remark', width: 120 },
    {
      title: '有效期', dataIndex: 'expireTime', width: 120,
      render: (v) => {
        const isValid = new Date(v).getTime() > Date.now();
        return <Tag color={isValid ? 'green' : 'red'}>{isValid ? '有效' : '已过期'}</Tag>;
      }
    },
    { title: '积分', dataIndex: 'printPoints', width: 100 },
    { title: '打印次数上限', dataIndex: 'printNumLimit', width: 120 },
    { title: '手机号', dataIndex: 'mobile', width: 120 },
    { title: '邮箱', dataIndex: 'email', width: 180 },
    { title: '创建者', dataIndex: 'createBy', width: 100 },
    { title: '创建时间', dataIndex: 'createTime', width: 160 },
    {
      title: '操作', dataIndex: 'actions', fixed: 'right', align: 'right', width: 200,
      render: (_, row) => (
        <Space>
          <Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(row)}>编辑</Button>
          <Button size="small" onClick={() => { setCurrentRow(row); setRenewOpen(true); }}>续费</Button>
          <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(row)}>删除</Button>
        </Space>
      )
    },
  ]), []);

  const handleSearch = async () => {
    const values = await form.validateFields().catch(() => null);
    if (!values) return;
    setLoading(true);
    setTimeout(() => {
      setData(prev => prev.filter(item => {
        const byTag = values.businessTagName ? item.tagName === values.businessTagName : true;
        const byNick = values.nickName ? item.nickName.includes(values.nickName) : true;
        const byAccount = values.account ? item.account.includes(values.account) : true;
        const byCreateBy = values.createBy ? item.createBy.includes(values.createBy) : true;
        return byTag && byNick && byAccount && byCreateBy;
      }));
      setLoading(false);
    }, 300);
  };

  const resetSearch = () => {
    form.resetFields();
    setData(Array.from({ length: 10 }).map((_, i) => ({
      id: i + 1,
      account: `temp_${i + 1}`,
      nickName: `临时用户${i + 1}`,
      tagName: i % 3 === 0 ? '活动A' : '活动B',
      remark: i % 2 === 0 ? '—' : '限时',
      expireTime: i % 3 === 0 ? '2023-12-31 23:59:59' : '2030-01-01 00:00:00',
      mobile: `1390000${String(200 + i)}`,
      email: `temp${i + 1}@example.com`,
      printPoints: Math.floor(Math.random() * 100),
      printNumLimit: Math.floor(Math.random() * 50),
      createBy: i % 2 === 0 ? 'admin' : 'operator',
      createTime: `2025-03-${(i % 28) + 1} 10:00:00`,
    })));
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  const handleDelete = (row) => {
    Modal.confirm({
      title: '删除临时用户',
      content: `将删除临时用户 ${row.nickName}（账号: ${row.account}）`,
      onOk: () => {
        setData(prev => prev.filter(d => d.id !== row.id));
        message.success('删除成功');
      },
    });
  };

  const handleEdit = (row) => {
    setCurrentRow(row);
    setEditOpen(true);
  };

  return (
    <div style={{ padding: 16 }}>
      <Card
        title={<Space><TeamOutlined />临时用户管理</Space>}
        extra={(
          <Space>
            <Button type="primary" icon={<TagsOutlined />} onClick={() => setTagOpen(true)}>标签管理</Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setNewOpen(true)}>新增临时用户</Button>
          </Space>
        )}
        style={{ marginBottom: 16 }}
      >
        <Form layout="inline" form={form} style={{ rowGap: 12 }}>
          <Form.Item name="businessTagName" label="用户标签">
            <Select allowClear placeholder="请选择" style={{ width: 160 }}>
              {tags.map(t => (<Option key={t.id} value={t.name}>{t.name}</Option>))}
            </Select>
          </Form.Item>
          <Form.Item name="nickName" label="昵称">
            <Input placeholder="昵称" allowClear style={{ width: 160 }} />
          </Form.Item>
          <Form.Item name="account" label="账号">
            <Input placeholder="账号" allowClear style={{ width: 160 }} />
          </Form.Item>
          <Form.Item name="createBy" label="创建者">
            <Input placeholder="创建者" allowClear style={{ width: 160 }} />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" onClick={handleSearch}>查询</Button>
              <Button onClick={resetSearch}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          loading={loading}
          rowSelection={rowSelection}
          pagination={{ pageSize: 10 }}
          size="small"
        />
      </Card>

      {/* 新增临时用户 */}
      <Modal
        title="新增临时用户"
        open={newOpen}
        onCancel={() => setNewOpen(false)}
        onOk={() => {
          const formId = 'temp-user-new-form';
          const formEl = document.getElementById(formId);
          if (!formEl) return;
          const values = Object.fromEntries(new FormData(formEl).entries());
          const newId = Math.max(...data.map(d => d.id)) + 1;
          setData(prev => [{
            id: newId,
            account: values.account || `temp_${newId}`,
            nickName: values.nickName || `临时用户${newId}`,
            tagName: values.tagName || '活动A',
            remark: values.remark || '—',
            expireTime: values.expireTime || '2030-01-01 00:00:00',
            mobile: values.mobile || '',
            email: values.email || '',
            printPoints: values.printPoints ? Number(values.printPoints) : 0,
            printNumLimit: values.printNumLimit ? Number(values.printNumLimit) : 0,
            createBy: 'admin',
            createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
          }, ...prev]);
          setNewOpen(false);
          message.success('新增临时用户成功');
        }}
        destroyOnClose
        width={720}
      >
        <form id="temp-user-new-form">
          <Space direction="vertical" style={{ width: '100%' }}>
            <Space>
              <Input name="account" placeholder="账号" style={{ width: 200 }} />
              <Input name="nickName" placeholder="昵称" style={{ width: 200 }} />
              <Select name="tagName" placeholder="用户标签" style={{ width: 200 }}>
                {tags.map(t => (<Option key={t.id} value={t.name}>{t.name}</Option>))}
              </Select>
            </Space>
            <Space>
              <Input name="mobile" placeholder="手机号" style={{ width: 200 }} />
              <Input name="email" placeholder="邮箱" style={{ width: 240 }} />
            </Space>
            <Space>
              <Input name="expireTime" placeholder="有效期(yyyy-MM-dd HH:mm:ss)" style={{ width: 320 }} />
            </Space>
            <Space>
              <InputNumber name="printPoints" placeholder="积分" style={{ width: 160 }} min={0} />
              <InputNumber name="printNumLimit" placeholder="打印次数上限" style={{ width: 200 }} min={0} />
            </Space>
            <Space>
              <Input name="remark" placeholder="备注" style={{ width: 520 }} />
            </Space>
          </Space>
        </form>
      </Modal>

      {/* 编辑临时用户 */}
      <Modal
        title="编辑临时用户"
        open={editOpen}
        onCancel={() => setEditOpen(false)}
        onOk={() => {
          const formId = 'temp-user-edit-form';
          const formEl = document.getElementById(formId);
          if (formEl) {
            const values = Object.fromEntries(new FormData(formEl).entries());
            setData(prev => prev.map(d => (d.id === currentRow.id ? {
              ...d,
              nickName: values.nickName || d.nickName,
              tagName: values.tagName || d.tagName,
              remark: values.remark || d.remark,
              printPoints: values.printPoints ? Number(values.printPoints) : d.printPoints,
              printNumLimit: values.printNumLimit ? Number(values.printNumLimit) : d.printNumLimit,
            } : d)));
            message.success('保存成功');
          }
          setEditOpen(false);
        }}
        destroyOnClose
      >
        <form id="temp-user-edit-form">
          <Space direction="vertical" style={{ width: '100%' }}>
            <Input name="nickName" defaultValue={currentRow?.nickName} placeholder="昵称" />
            <Select name="tagName" defaultValue={currentRow?.tagName} placeholder="用户标签" style={{ width: 200 }}>
              {tags.map(t => (<Option key={t.id} value={t.name}>{t.name}</Option>))}
            </Select>
            <InputNumber name="printPoints" defaultValue={currentRow?.printPoints} placeholder="积分" min={0} />
            <InputNumber name="printNumLimit" defaultValue={currentRow?.printNumLimit} placeholder="打印次数上限" min={0} />
            <Input name="remark" defaultValue={currentRow?.remark} placeholder="备注" />
          </Space>
        </form>
      </Modal>

      {/* 续费弹窗（简版） */}
      <Modal
        title="续费临时用户"
        open={renewOpen}
        onCancel={() => setRenewOpen(false)}
        onOk={() => { setRenewOpen(false); message.success('续费成功'); }}
      >
        <Space>
          {[
            { label: '1个月', value: 1 },
            { label: '3个月', value: 3 },
            { label: '12个月', value: 12 },
          ].map(item => (
            <Button
              key={item.value}
              type={renewalType === item.value ? 'primary' : 'default'}
              onClick={() => setRenewalType(item.value)}
            >{item.label}</Button>
          ))}
        </Space>
        <div style={{ marginTop: 12 }}>当前用户：{currentRow?.nickName}（账号：{currentRow?.account}）</div>
      </Modal>

      {/* 标签管理（简版） */}
      <Modal
        title="用户标签管理"
        open={tagOpen}
        onCancel={() => setTagOpen(false)}
        onOk={() => setTagOpen(false)}
        destroyOnClose
      >
        <Space wrap>
          {tags.map(t => <Tag key={t.id} closable onClose={() => setTags(prev => prev.filter(x => x.id !== t.id))}>{t.name}</Tag>)}
        </Space>
        <Space style={{ marginTop: 12 }}>
          <Input id="new-temp-user-tag-name" placeholder="新增标签名称" style={{ width: 200 }} />
          <Button type="primary" onClick={() => {
            const el = document.getElementById('new-temp-user-tag-name');
            const name = el?.value?.trim();
            if (!name) return;
            const newId = Math.max(...tags.map(t => t.id)) + 1;
            setTags(prev => [...prev, { id: newId, name }]);
            message.success('新增标签成功');
            el.value = '';
          }}>新增</Button>
        </Space>
      </Modal>
    </div>
  );
}